﻿using System;
using System.Threading;
using System.Threading.Tasks;
using System.Net.WebSockets;
namespace MVCDemo.Chat
{
    public class AsyncReceive
    {
        private const int BufferSize = 1024;
        private WebSocket _socket { get; set; }
        public AsyncReceive(WebSocket socket)
        {
            _socket = socket;
        }
        public  async Task ProcessReceive()
        {
            var buffer = new byte[BufferSize];
            var seg = new ArraySegment<byte>(buffer);

            while (_socket.State == WebSocketState.Open)
            {
                var incoming = await _socket.ReceiveAsync(seg, CancellationToken.None);
                if (incoming.Count > 0)
                {
                    byte[] b = new byte[incoming.Count];
                    Array.Copy(buffer, b, b.Length);
                    MessageDealWidth.DealWidth(b, _socket);
                    Array.Clear(buffer, 0, buffer.Length);
                }
            }
            if (_socket.State != WebSocketState.Open)
            {
                try
                {
                    string tokenId = string.Empty;
                    //当用户处于离线状态时从连接池中删除该对象
                    foreach (AsyncUserToken token in ConnectionManager.Connections.Values)
                    {
                        if (token.ConnectSocket == _socket)
                        {
                            tokenId = token.TokenId;
                            break;
                        }
                    }
                    AsyncUserToken userToken = null;
                    ConnectionManager.Connections.TryRemove(tokenId, out userToken);
                }
                catch { }
            }
        }
    }
}
